package com.coolgor.axnut.web.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FileController {

    private static final Logger log = LoggerFactory.getLogger(FileController.class);
    //设置文件存储路径
    private static final String FilePath = "D:\\AxnutFile\\";

    @RequestMapping(value = "/upload")
    @ResponseBody
    public Map<String, Object> uploadFile(@RequestParam("filelist") MultipartFile[] filelist) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        try {
            // 判断列表是否为空
            if(filelist == null || filelist.length == 0){
                modelMap.put("success", false);
                modelMap.put("errMsg", "filelist is empty");
                return modelMap;
            }
            Map<String, String> uploadFileList = new HashMap<String, String>();
            for( MultipartFile file : filelist){
                if (file.isEmpty()) {
                    log.info("[ 文件传输异常 >>> " + file.getOriginalFilename() + " 文件为空！");
                }
                //获取文件名
                String fileName = file.getOriginalFilename();
                //获取文件扩展名
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
//                log.info("[ 正在上传 >>> "+fileName+"."+suffixName);
                log.info("[ 正在上传 >>> " + fileName);
                SimpleDateFormat dateFormat=new SimpleDateFormat("YYYYMMdd");
//                String path = FilePath + dateFormat.format(new Date()) + "\\" +fileName ;
                String path = FilePath + dateFormat.format(new Date())
                        + "\\" + System.currentTimeMillis() + suffixName;
                File dest = new File(path);
                //检查是否存在目录
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                file.transferTo(dest); //文件写入
                uploadFileList.put( fileName, path );
            }
            modelMap.put("success", true);
            modelMap.put("uploadlist", uploadFileList);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return modelMap;
    }

    @RequestMapping("download")
    public void download(HttpServletResponse response) throws Exception {
        // 文件地址，真实环境是存放在数据库中的
        File file = new File("D:\\upload\\a.txt");
        // 创建输入对象
        FileInputStream fis = new FileInputStream(file);
        // 设置相关格式
        response.setContentType("application/force-download");
        // 设置下载后的文件名以及header
        response.addHeader("Content-disposition", "attachment;fileName=" + "a.txt");
        // 创建输出对象
        OutputStream os = response.getOutputStream();
        // 常规操作
        byte[] buf = new byte[1024];
        int len = 0;
        while((len = fis.read(buf)) != -1) {
            os.write(buf, 0, len);
        }
        fis.close();
    }
}
